package com.geekaca.db;

import com.geekaca.db.mapper.UserMapper;
import com.geekaca.db.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestUser {
    public static void main(String[] args) {
//        updateUser();
//        delectUserById();
//        selectUsersByIds();
        userLogin("Tom18", "123");
        userLogin("Tom17", "123456");
        userLogin("Tom_cat", "123456");
    }

    // 作业1, 通过用户名查到对象, 然后传入对象调用更新方法,对象自带id,
    private static void updateUser() {
        SqlSession sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        // 通过用户名查找用户,返回用户对象
        User user = userMapper.selectUsers("Tom_cat");
        System.out.println("查询到的用户为: " + user);

        //  更新用户的信息
        user.setPwd("123456");
//        user.setAge(28);
        user.setTel("13928546259");
        user.setVersion(4);
        userMapper.updateUsers(user);
    }

    // 作业2, 单个id删除
    private static void delectUserById() {
        SqlSession sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        int delected = userMapper.deleteById(17);
        if (delected == 1) {
            System.out.println("删除成功");
        }
    }

    // 作业3, 多个id 查询用户;
    private static void selectUsersByIds() {
        SqlSession sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 查询 id 为 1,4,15 的用户
        List<User> users = userMapper.selectUsersByIds(new int[]{1, 4, 15});
        if (users != null) {
            users.forEach(user -> System.out.println("查询到用户: " + user));
        }
    }

    // 作业4  模拟用户登录
    private static void userLogin(String username, String password) {
        SqlSession sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectByNamePass(username, password);
        if (user != null) {
            System.out.println("用户 " + username + " 登录成功");
        } else {
            System.out.println("用户 " + username + "登录失败");
        }
    }

    // 创建数据操作会话
    private static SqlSession openSession() {
        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream ips = null;
        try {
            ips = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //2. 获取SqlSession 对象, 用农来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }
}
